import { getStuShowList, stuShowCreate, getStuShowDetail } from "@/request/stushow.js";
import { Message } from 'ant-design-vue';
const state = {
  stuShowList: [],
  markGetStuShowList: false, //标记是否已经获取了数据
  defaultData: {
    userID: null,
    currNo: null,
    homepagepath: ``,
    filepaths: [],
    state: '公开',
    grade: '优秀'
  }
}

const mutations = {
  // 更改学业列表数据
  setStuShowList(state, payload) {
    state.stuShowList = payload
  },
  // 更新后的学业数据
  stushowDataUpadateToList(state, payload) {
    let findStuShowData = state.stuShowList.find(item => item.stuworkshowID == payload.stuworkshowID)
    // 合并对象数据
    Object.assign(findStuShowData, payload)
  },
  // 
  setMarkGetStuShowList(state, payload) {
    state.markGetStuShowList = payload
  }
}

const actions = {

  // 获取学业展示列表数据
  async fetchStuShowListByUserID({ commit, state, dispatch }, val) {
    commit("setMarkGetStuShowList", true)
    const res = await getStuShowList(val);
    if (res.errno === 0) {
      commit("setStuShowList", res.data)
      return res.data
    } else {
      commit("setMarkGetStuShowList", false)
      Message.error({ content: '获取学业列表失败' })
      return false
    }
  },
  // 获取学业展示列表store数据
  async gStuShowList({ commit, state, dispatch }, val) {
    if (!state.markGetStuShowList) {
      const data = await dispatch("fetchStuShowListByUserID", val)
      if (data) return data
      else return false
    } else {
      return state.stuShowList
    }
  },
  // 创建学业
  async createStuOutcomes({ commit, state, dispatch }, payload) {
    const currNo = payload.currNo
    const userID = payload.userID
    const that = payload.that
    const params = state.defaultData
    params.userID = userID
    params.currNo = currNo
    const res = await stuShowCreate(params)
    if (res.errno === 0) {
      if (that) {
        const findCourse = that.tableData.find(item => item.currNo == currNo)
        that.$set(findCourse, "stuShow", true)
        that.$set(findCourse, "stuShowData", res.data)
      }
      // 创建学业后将新的学业数据合并到数组
      let stuShowList = [state.stuShowList, ...[res.data]]
      commit("setStuShowList", stuShowList)
      Message.success({ content: '学业创建成功!' })
      return true
    } else {
      Message.error({ content: res.message || '创建失败!' })
      return false
    }
  },
  fetchStuShowDataByID({ commit, state, dispatch}, params) {
    return new Promise((resolve, reject) => {
      getStuShowDetail(params).then(res => {
        if (res.errno == 0) {
          resolve(res.data)
        } else {
          resolve(false)
        }
      }).catch(err =>{
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}